#include <MenuButton.h>

#include <World.h>
#include <Command.h>

#include <glut.h>

MenuButton::MenuButton(std::string text, World& gameworld, Command* cmd, vec2 pos, float w, float h)
:buttonText(text)
,world(gameworld)
,command(cmd)
,bottomLeft(pos)
,size(w,h)
,brightness(0.5f)
,color(0,1,0.5f)
{
	command->managed = CommandType::NON_MANAGED;

	vertices[0] = bottomLeft;
	vertices[1] = bottomLeft + vec2(0,size.y);
	vertices[2] = bottomLeft + size;
	vertices[3] = bottomLeft + vec2(size.x,0);	
}

MenuButton::~MenuButton()
{
}
	
void MenuButton::SetColor(float r, float g, float b)
{
	color.Set(r,g,b);
}

void MenuButton::Update()
{
	truth mouseOver = MouseOver();
	if( mouseOver )
		brightness = 2.0f;
	else
		brightness = 1.0f;

	if( mouseOver && Global::Mouse::ButtonStates & Button::LEFT_DOWN )
		OnClick();
}

void MenuButton::Draw()
{
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	int w = glutGet(GLUT_WINDOW_WIDTH);
	int h = glutGet(GLUT_WINDOW_HEIGHT);
	gluOrtho2D(0, w, h, 0);
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();

	glEnable(GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glColor4f(0.5f * color.r * brightness, 0.5f * color.g * brightness, 0.5f * color.b * brightness, 0.5f);
	glBegin(GL_TRIANGLE_FAN);
	for (int32 i = 0; i < 4; ++i)
	{
		glVertex2f(vertices[i].x, vertices[i].y);
	}
	glEnd();
	glDisable(GL_BLEND);

	glColor4f(color.r * brightness, color.g * brightness, color.b * brightness, 1.0f);
	glBegin(GL_LINE_LOOP);
	for (int32 i = 0; i < 4; ++i)
	{
		glVertex2f(vertices[i].x, vertices[i].y);
	}
	glEnd();

	if( !buttonText.empty() )
	{
		glColor3f(0.9f, 0.6f, 0.6f);
		glRasterPos2i(bottomLeft.x + size.x*0.2f, bottomLeft.y + size.y*0.6f);
		int32 length = (int32)buttonText.size();
		std::string::iterator sIter = buttonText.begin();
		for (; sIter != buttonText.end(); ++sIter)
			glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *sIter);
	}

	glPopMatrix();
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
}

void MenuButton::OnClick()
{
	command->managed = CommandType::NON_MANAGED;
	world.AddCommand( command );
	//world.SetMainMenu( 0 ); //TODO: remove <-
}

truth MenuButton::MouseOver()
{
	if( Global::Mouse::ScreenPos.x < bottomLeft.x )
		return 0;
	if( Global::Mouse::ScreenPos.y < bottomLeft.y )
		return 0;
	if( Global::Mouse::ScreenPos.x > bottomLeft.x+size.x )
		return 0;
	if( Global::Mouse::ScreenPos.y > bottomLeft.y+size.y )
		return 0;
	return 1;
}
